package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.dto.CollectionDTO;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.CollectionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/autotest/collection")
public class CollectionController {

    @Autowired
    private CollectionService collectionService;

    @PostMapping("/save")
    public void saveCollection(@RequestBody CollectionDTO collectionDTO, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        collectionDTO.setUpdateUser(userName);
        collectionService.saveCollection(collectionDTO);
    }

    @PostMapping("/delete")
    public void deleteCollection(@RequestBody CollectionDTO collectionDTO) {
        collectionService.deleteCollection(collectionDTO);
    }

    @GetMapping("/detail/{collectionId}")
    public CollectionDTO getCollectionDetail(@PathVariable String collectionId){
        return collectionService.getCollectionDetail(collectionId);
    }

    @GetMapping("/types/{collectionId}")
    public Map<String, Boolean> getCollectionCaseTypes(@PathVariable String collectionId){
        return collectionService.getCollectionCaseTypes(collectionId);
    }

    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<CollectionDTO>> getCollectionList(@PathVariable int goPage, @PathVariable int pageSize,
                                           @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, collectionService.getCollectionList(request));
    }
}
